<?php
require_once("config/config.inc.php");

/**
* login authentication
*/

if( isset($_POST) ) {
	$user = $_POST["uname"];
	$pass = $_POST["pword"];
	
	$sql = "select a.user_id, a.group_id, b.group_name, a.fullname 
		from users a, groups b
		where a.group_id=b.group_id
		and a.username=binary('$user') 
		and a.userpass=binary('$pass')
		
	";
	$res = mysql_query($sql) or die(JSON_encode(array('success'=>false,'msg'=>"Authentication $user failed. Please contact your administrator." . $sql)));
	if(mysql_num_rows($res)) {
		list($userid,$groupid,$groupname,$fullname)=mysql_fetch_row($res);
		session_start();
		$_SESSION["hotel"]["logged"]=true;
		$_SESSION["hotel"]["userid"]=$userid;
		$_SESSION["hotel"]["groupid"]=$groupid;
		$_SESSION["hotel"]["groupname"]=$groupname;
		$_SESSION["hotel"]["fullname"]=$fullname;
		$shiftstatus = hasShiftStart();
		$msg[0]= 'Identity confirmed. Please perform shift start activities first.';
		$msg[1] = 'Identity confirmed. Welcome ' . $fullname;
		
		$resp = array('success'=>true, 'msg'=> $msg[$shiftstatus], 'shiftstatus'=>$shiftstatus);
		$json =  JSON_encode($resp);
		accessLogs($userid,"Login",$json);
		echo $json;
	}else{
		$resp = array('success'=>false,'msg'=>"Authentication $user failed. Please contact your administrator."  );
		$json =  JSON_encode($resp);
		accessLogs('0',"Login",$json);
		echo $json;
	}
}

function hasShiftStart()
{
	$sql = "select shift from `shift-transactions` order by datetime desc limit 0,1";
	$res = mysql_query($sql) or die($sql);
	list($shift)=mysql_fetch_row($res);
	if($shift=='end')
	{
		return 0;
	}
	return 1;
}